package com.ebeitech.auction.view.homepage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.ebeitech.auction.R;
import com.ebeitech.auction.application.EbeiApplication;
import com.ebeitech.auction.constants.ActionConstants;
import com.ebeitech.auction.constants.CommonConstants;
import com.ebeitech.auction.http.EbeiErrorCode;
import com.ebeitech.auction.http.HttpService;
import com.ebeitech.auction.http.model.LoginModel;
import com.ebeitech.auction.http.model.LoginWeiXinModel;
import com.ebeitech.auction.http.model.VersionModel;
import com.ebeitech.auction.http.service.HttpAuctionServiceRx;
import com.ebeitech.auction.view.PublicUtil;
import com.ebeitech.auction.view.homepage.mvppresenter.LoginPresenterModule;
import com.ebeitech.auction.view.homepage.mvpview.LoginContract;
import com.ebeitech.auction.view.homepage.mvpview.DaggerLoginComponent;
import com.ebeitech.land.auction.wxapi.WeiXinUtil;
import com.ebeitech.library.ui.dialog.*;
import com.ebeitech.library.util.CommonUtil;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.VersionUtil;
import com.ebeitech.library.util.ViewUtil;
import com.ebeitech.library.util.view.StatusBarCompat;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class LoginActivity extends BaseActivity implements LoginContract.View {


	@BindView(R.id.etUserName)
	EditText etUserName;
	@BindView(R.id.etPassword)
	EditText etPassword;
	@BindView(R.id.btnLogin)
	Button btnLogin;
	@BindView(R.id.loginFrame)
	LinearLayout loginFrame;
	@BindView(R.id.view_login_from_other)
	View viewLoginFromOther;

	CommonAlertDialogFragment mProgressDialog;
	private boolean isBind;
	private LoginWeiXinModel mLoginWeiXinModel;

	@Inject
	LoginContract.Presenter presenter;

	private boolean isHomeShowVersionDialog = false;

	private boolean isLogout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_login);
		ButterKnife.bind(this);
		DaggerLoginComponent.builder()
				.loginPresenterModule(new LoginPresenterModule(this))
				.build()
				.inject(this);

		if(!CommonUtil.isNetworkAvailable(this)){
			ViewUtil.toastMsg(this, R.string.ebei_network_disconnect);
		}

		Intent intent = getIntent();
		if (intent != null) {
			isBind = intent.getBooleanExtra("isBind", false);
			mLoginWeiXinModel = (LoginWeiXinModel) intent.getSerializableExtra("loginWeiXinModel");
			isLogout = intent.getBooleanExtra("isLogout",false);
		}

		initView();
		registerBroadCast();
	}

	@OnClick({R.id.btnLogin, R.id.btnLoginWeiXin})
	void onClick(View view) {
		switch (view.getId()) {
			case R.id.btnLogin: {
				SPManager.getInstance().put("isDialogShowing", false);
				if(StringUtil.isEmpty(etUserName.getText().toString())){
					ViewUtil.toastMsg(this, R.string.ebei_login_account_null);
					return;
				}
				if(StringUtil.isEmpty(etPassword.getText().toString())){
					ViewUtil.toastMsg(this, R.string.ebei_login_password_null);
					return;
				}

				String mPassword = etPassword.getText().toString();
				if (!isBind) {
					presenter.doLogin(etUserName.getText().toString(), mPassword);
					return;
				}
				presenter.doBindWeiXin(mLoginWeiXinModel.getAccess_token(), etUserName.getText().toString(), mPassword);
				break;
			}
			case R.id.btnLoginWeiXin: {
				SPManager.getInstance().put("isDialogShowing", false);
				if(!CommonUtil.isNetworkAvailable(this)){
					ViewUtil.toastMsg(this, R.string.ebei_network_disconnect);
					return;
				}

				String mPassword = etPassword.getText().toString();
				presenter.doWeiXinLogin(etUserName.getText().toString(), mPassword);
				break;
			}
		}
	}

	private void initView() {
		// 如果之前被挤下线,弹框提醒
		boolean isLoginOfflineRemind = SPManager.getInstance().get(CommonConstants.IS_LOGIN_OFFLINE_REMIND, true);
		if (!isLoginOfflineRemind) {
			SPManager.getInstance().put(CommonConstants.IS_LOGIN_OFFLINE_REMIND, true);
			final Context context = EbeiApplication.getContext();// 防止context不正确,DialogFragment报错
			CommonAlertDialogFragment dialog = ViewUtil.getAlertDialog(context, "", context.getString(R.string.login_with_another_client), new CommonAlertDialogFragment.OnBtnClickListener() {
				@Override
				public void onClick(View v, CommonAlertDialogFragment dialog) {
					ViewUtil.dismissDialog(dialog);
					PublicUtil.doLogout(context);
				}
			}, null, "", "");
			dialog.setCancelButtonVisible(false);
			ViewUtil.showDialog(context, dialog);
			loginFrame.setVisibility(View.VISIBLE);
		} else {
			loginFrame.setVisibility(View.GONE);
			presenter.autoLogin(this);
		}
		if (isBind) {
			btnLogin.setText(R.string.ebei_bind_and_login);
			viewLoginFromOther.setVisibility(View.GONE);
		}
	}

	@Override
	public void showProgress(String message) {
		mProgressDialog = ViewUtil.showProgressDialog(this, "", message);
	}

	@Override
	public void dismissProgress() {
		ViewUtil.dismissDialog(mProgressDialog);
	}

	@Override
	public void showLoginResult(String resultMessage) {
		if(!StringUtil.isEmpty(resultMessage)){
			ViewUtil.toastMsg(this,resultMessage);
		}
	}

	@Override
	public void loginSuccess() {
		SPManager.getInstance().put(CommonConstants.IS_LOGIN_OFFLINE, false);
		HttpService.getInstance().resetHttp();
		ViewUtil.toastMsg(this, R.string.ebei_login_success, 500);
		Intent intent = new Intent();
		intent.setClass(this, HomepageActivity.class);
		intent.putExtra("isHomeShowVersionDialog",isHomeShowVersionDialog);
		startActivity(intent);
		setResult(RESULT_OK, null);
		finish();
	}

	@Override
	public void setIsHomeShowVersionUpdateDialog(boolean flag) {
		isHomeShowVersionDialog = flag;
	}

	@Override
	public void showLoginFrame() {
		loginFrame.setVisibility(View.VISIBLE);
		if (!isLogout)
			PublicUtil.checkVersion(this);
	}

	@Override
	public void showUserAccount(String userAccount, String password) {
		etUserName.setText(StringUtil.getDefaultString(userAccount));
	}

	private void registerBroadCast() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(ActionConstants.ACTION_EXIT_APP);
		myIntentFilter.addAction(WeiXinUtil.ACTION_WEIXIN_LOGIN);
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (ActionConstants.ACTION_EXIT_APP.equals(action)) {
			} else if (WeiXinUtil.ACTION_WEIXIN_LOGIN.equals(action)) {
				LoginWeiXinModel loginWeiXinModel = (LoginWeiXinModel) intent.getSerializableExtra("loginWeiXinModel");
				if (loginWeiXinModel != null) {
					LoginModel loginModel = loginWeiXinModel.getUser();
					if (loginModel != null && "1".equals(loginModel.getResultCode())
							&& loginModel.getData() != null && loginModel.getData().getUserVO() != null) {
						presenter.loginSuccess(loginModel);
					} else {
						// 调到绑定页面
						Intent intent1 = new Intent(LoginActivity.this, LoginActivity.class);
						intent1.putExtra("isBind", true);
						intent1.putExtra("loginWeiXinModel", loginWeiXinModel);
						startActivityForResult(intent1, 1);
					}
				} else {
					ViewUtil.toastMsg(getApplicationContext(), R.string.ebei_login_weixin_failure);
				}
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				finish();
			}
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}


}
